package com.laikan.reader.apirequester;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.LaikanApplication;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.VersionDetialInfo;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.service.AppUpdateService;
import com.laikan.reader.core.utils.BookFileUtils;
import com.laikan.reader.core.utils.FileUtil;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.utils.SystemUtil;
import com.laikan.reader.core.view.VersionUpdateDialog;
import com.socks.library.KLog;

import java.io.File;
import java.lang.reflect.Type;

/**
 * Created by anrun on 7/22/16.
 */
public class UpdateUtil {

    /**
     * 检查版本更新
     */
    public static void showUpdateDialog(final VersionDetialInfo detailInfo, final Context context) {
        try {
            final VersionUpdateDialog dialog = new VersionUpdateDialog(context);
            dialog.show();
            dialog.setTipContent(detailInfo.getMsg());
            dialog.setUpdateNowListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 点击更新，后台service下载程序，完成后提示安装即可。
                    if(isServiceRunning(context)){
                        ToastMgr.showShortToast(R.string.chapter_downing);
                        dialog.dismiss();
                        return;
                    }
                    ToastMgr.showShortToast(R.string.chapter_down_start);
                    dialog.dismiss();
                    Intent intent = new Intent();
                    intent.setClass(context, AppUpdateService.class);
                    intent.putExtra("updateBean", detailInfo);
                    context.startService(intent);
                }
            });

            dialog.setUpdateLaterListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        }catch (Exception e) {
        }
    }
    // 更新版本Service是否已经运行
    public static boolean isServiceRunning(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if(service != null){
                if (AppUpdateService.class.getName().equals(service.service.getClassName())) {
                    return true;
                }
            }
        }

        return false;
    }

    public static void checkVersion(final Context context, final boolean isShowToast) {
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                BaseDataBean<VersionDetialInfo> result;
                Gson gson = new Gson();
                try {
                    Type type = new TypeToken<BaseDataBean<VersionDetialInfo>>() {}.getType();
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (Constants.RESULT_OK.equals(result.getResult())) {
                        VersionDetialInfo detailInfo = result.getData();
                        String messageversion = detailInfo.getMessageVersion();
                        if(!SPUtil.getString("version","2").equals(messageversion)){
                            SPUtil.putBoolean("update_message",true); //记录个人中心消息红点显示
                            SPUtil.putString("version",messageversion); //记录消息的新状态值
                        }
                        if (LaikanApplication.mAppVersion.compareTo(detailInfo.getVersion()) < 0) {
                            // 有新版本可升级,弹出下载升级提示框
                            SPUtil.putBoolean("checkversion_update",true);
                            UpdateUtil.showUpdateDialog(detailInfo, context);
                        }else {
                            SPUtil.putBoolean("checkversion_update",false);
                            if (isShowToast) {
                                ToastMgr.showShortToast(R.string.bookfriend_personalactivity_version_latest);
                            }
                        }
                        SystemUtil.checkRedDotShow();
                        LaiKanEvent laiKanEvent = LaiKanEvent.getInstance();
                        laiKanEvent.setEventID(LaiKanEvent.EVENT_ID_UPDATE_VERSION);
                        LaikanApplication.postEvent(laiKanEvent);
                        //启动页直接访问本地,不再去服务器下载
//                        downLoadSplashImg(detailInfo.getMsgUrl(), context);
                    }else {
                        ToastMgr.showShortToast(result.getError_msg());
                    }
                }catch (Exception e) {
                    KLog.e("版本检查异常");
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {

            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_check_version);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);
    }

    /**
     * 下载启动页图片
     *
     * @param msgUrl 启动页图片url
     */
    public static void downLoadSplashImg(String msgUrl, Context mContext) {
        String splash_msgUrl = SPUtil.getString("splash_msgUrl", "");
        File file = new File(PublicUtil.getRootPath() + BookFileUtils.SPLASHIMGFILEPATH + "/lk_splash_bg.png");

        if (!TextUtils.isEmpty(msgUrl)) {
            // 下载启动页图片
            if (file.exists() && file.length() != 0 && splash_msgUrl.equals(msgUrl)) {
                // 缓存图片存在并且url与服务器一致,不需要重新下载
                KLog.e("1343-0 缓存图片存在并且url与服务器一致,不需要重新下载");
                return;
            }else if (!file.exists() || file.length() == 0 || !splash_msgUrl.equals(msgUrl)) {
                SPUtil.putString("splash_msgUrl", msgUrl);
                // 有新启动图片的时候,下载新启动页图片
                FileUtil.downloadSplashImg(mContext, msgUrl,"");
                KLog.e("1343-2 有新启动图片的时候,下载新启动页图片");
            }

        }else {
            // 删除启动页图片
            FileUtil.deleteFile(file);
            SPUtil.putString("splash_msgUrl", "");
            KLog.e("1343-4 无启动任务图片,将之前缓存本地的图片删除");
        }
    }

    /**
     * 下载广告页图片
     * @param msgUrl 广告页图片url
     */
    public static void downLoadPosterImg(String msgUrl, Context mContext, String isPosterImg) {
        String poster_msgUrl = SPUtil.getString("poster_msgUrl", "");
        File file = new File(PublicUtil.getRootPath() + BookFileUtils.POSTERIMGFILEPATH + "/lk_poster_bg.png");

        if (!TextUtils.isEmpty(msgUrl)) {
            // 下载广告页图片
            if (file.exists() && file.length() != 0 && poster_msgUrl.equals(msgUrl)) {
                // 缓存图片存在并且url与服务器一致,不需要重新下载
                KLog.e("广告: 缓存图片存在并且url与服务器一致,不需要重新下载");
                return;
            }else if (!file.exists() || file.length() == 0 || !poster_msgUrl.equals(msgUrl)) {
                SPUtil.putString("poster_msgUrl", msgUrl);
                // 有新广告图片的时候,下载新广告页图片
                FileUtil.downloadSplashImg(mContext, msgUrl,isPosterImg);
                KLog.e("广告 : 有新启动图片的时候,下载新启动页图片");
            }

        }else {
            // 删除广告页图片
            FileUtil.deleteFile(file);
            SPUtil.putString("poster_msgUrl", "");
            KLog.e("无广告页图片,将之前缓存本地的图片删除");
        }
    }
}
